package com.winning.pmph.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.winning.pmph.entity.ExerciseBook;
import com.winning.pmph.entity.ExerciseEntry;
import com.winning.pmph.entity.ExerciseGroup;
import com.winning.pmph.mapper.ExerciseGroupMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.stream.Collectors;

@Component
@Transactional
public class ExerciseGroupService extends ServiceImpl<ExerciseGroupMapper, ExerciseGroup> {

    @Resource
    private ExerciseEntryService exerciseEntryService;

    public void updateExerciseGroup(ExerciseGroup exerciseGroup) {
        // case_alias 与 entry 保持一致;
        if (StringUtils.equals(exerciseGroup.getRole(), ExerciseGroup.ROLE_A1)
            || StringUtils.equals(exerciseGroup.getRole(), ExerciseGroup.ROLE_B)) {
            String caseAlias = exerciseGroup.getExerciseEntryList().stream().map(ExerciseEntry::getQuestion).collect(Collectors.joining(System.lineSeparator()));
            exerciseGroup.setCaseAlias(caseAlias);
        }
        // B型题, 共用选项, 以第一题为准;
        if (StringUtils.equals(exerciseGroup.getRole(), ExerciseGroup.ROLE_B)) {
            exerciseGroup.getExerciseEntryList().forEach(exerciseEntry -> exerciseEntry.setChoiceArray(exerciseGroup.getExerciseEntryList().get(0).getChoiceArray()));
        }
        updateById(exerciseGroup);
        // 保存 entityList;
        exerciseEntryService.saveOrUpdateBatch(exerciseGroup.getExerciseEntryList());
    }
}
